// pages/leader/apply/apply.js
import * as API_Address from '../../../api/address'
import * as API_Distribution from '../../../api/distribution'
import * as API_Leader from '../../../api/leader'
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 当前身份状态
    distributState: 0,
    pointState: 0,
    hasDistribut: false,
    hasPoint: false,
    // 申请类型
    isDistribut: true,
    isPoint: false,
    // 基础信息
    leader_name: '',
    midentity: '',
    lv1_invite_code: '',
    join_reason: '',
    // 门店信息
    cell_name: '',
    site_name: '',
    site_type: '',
    region_text: '',
    address: '',
    lat: '',
    lng: '',
    // 店铺类型
    shopType: [
      { type: 0, name: '快递站' },
      { type: 1, name: '便利店' },
      { type: 2, name: '小卖部' },
      { type: 3, name: '小超市' },
      { type: 4, name: '洗衣店' },
      { type: 5, name: '其他' }
    ],
    // 地址信息
    region: 0,
    subDisabled: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    await app.getUserAllInfo();
    const _userData = wx.getStorageSync('user');
    const _distributData = wx.getStorageSync('distributor');
    const _leaderData = wx.getStorageSync('leader');
    let { distributState, pointState, hasDistribut, hasPoint } = this.data;
    let pageData = {
      leader_name: _userData.real_name,
      midentity: _userData.midentity
    };
    if (_distributData) {
      distributState = _distributData.audit_status;
      if (distributState === 1 || distributState === 2) {
        pageData = {
          ...pageData,
          isPoint: true,
          join_reason: _distributData.apply_reason
        };
      };
      pageData.lv1_invite_code = _distributData.lv1_invite_code;
      if (distributState === 0 && options.inviteCode) {
        pageData.lv1_invite_code = options.inviteCode;
      }
    };
    if (_leaderData) {
      pointState = _leaderData.audit_status;
      pageData = {
        ...pageData,
        isPoint: true,
        join_reason: _leaderData.join_reason,
        cell_name: _leaderData.cell_name,
        site_name: _leaderData.site_name,
        site_type: _leaderData.site_type,
        region_text: `${_leaderData.province}${_leaderData.city}${_leaderData.town}`,
        address: _leaderData.address,
        lat: _leaderData.lat,
        lng: _leaderData.lng
      };
    };
    hasDistribut = distributState && (distributState === 1 || distributState === 2);
    hasPoint = pointState && (pointState === 1 || pointState === 2);
    this.setData({
      ...pageData,
      distributState,
      pointState,
      hasDistribut,
      hasPoint
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  // 分销团长勾选
  applyDistribut () {
    let { isDistribut } = this.data;
    this.setData({
      isDistribut: !isDistribut
    });
  },
  // 自提站点勾选
  applyPoint () {
    let { isPoint } = this.data;
    this.setData({
      isPoint: !isPoint
    });
  },
  // 显示默认邀请码
  showDefaultCode () {
    const that = this;
    wx.showModal({
      title: '没有上级团长邀请码?',
      content: '请使用官方邀请吗: 000001',
      confirmText: '使用',
      cancelText: '取消',
      confirmColor: '#e50c0c',
      cancelColor: '#cdcdcd',
      success(res) {
        if (res.confirm) {
          that.setData({
            lv1_invite_code: '000001'
          });
        } else if (res.cancel) {
          console.log('取消使用官方邀请码');
        };
      }
    });
  },
  // 店铺类型
  bindPickerChange: function (e) {
    this.setData({
      'site_type': e.detail.value,
    });
  },
  // 显示地图地址
  showMap () {
    let that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.address && res.name) {
          that.formatAddress(res.longitude, res.latitude, res.address);
        };
      }
    });
  },
  // 获取省市区
  formatAddress (longitude, latitude, addr) {
    API_Address.getNearby(longitude, latitude).then(resposnse => {
      let { address_component, location } = resposnse;
      let { province, city, district } = address_component;
      let { lat, lng } = location;
      let address = addr;
      let _pcd = `${city}${district}`;
      if (province !== city) {
        _pcd = `${province}${_pcd}`;
      };
      if (address.indexOf(_pcd) > -1) {
        address = address.replace(_pcd, '');
      };
      this.setData({
        'region_text': _pcd,
        'address': address,
        'lat': lat,
        'lng': lng
      });
      this.getAreasNum(province, city, district);
    });
  },
  //获取地区列表
  getAreasNum(province, city, district) {
    let _params = {
      'province_name': province,
      'city_name': city,
      'area_name': district,
    };
    API_Address.getAreasNum(_params).then(response => {
      this.setData({
        region: response.countyId
      });
    })
  },
  // 提交团长申请
  async submitApply(e) {
    let _isLogin = await app.isLogin();
    if (!_isLogin) { return };
    const { isDistribut, isPoint } = this.data;
    if (!isDistribut && !isPoint) {
      wx.showToast({
        title: '请选择申请类型',
        icon: 'none'
      });
    } else {
      this.setData({
        subDisabled: true
      });
      const { hasDistribut, hasPoint } = this.data;
      let _formVal = e.detail.value;
      let { site_name, leader_name, region_text, address } = _formVal;
      let _toast = '';
      if (!leader_name) {
        _toast = '请填写真实姓名！';
      } else if (!hasPoint && isPoint) {
        if (!site_name) {
          _toast = '请填写店铺名称！';
        } else if (!region_text) {
          _toast = '请选择省市区！';
        } else if (!address) {
          _toast = '请填写详细地址！';
        };
      };
      if (_toast) {
        wx.showToast({
          title: _toast,
          icon: 'none'
        });
        this.setData({
          subDisabled: false
        });
        return;
      };
      if (!hasDistribut && isDistribut) {
        this.serviceApplyDistribut(_formVal);
        app.sendNotice('DISTRIBUTION_NOTICE_1,DISTRIBUTION_NOTICE_2');
      };
      if (!hasPoint && isPoint) {
        this.serviceApplyDPoint(_formVal);
        app.sendNotice('PICK_NOTICE_1,PICK_NOTICE_2');
      };
    };
  },
  // 提交分销团长申请
  serviceApplyDistribut (_form) {
    const { leader_name, midentity, lv1_invite_code, join_reason } = _form;
    let _params = {
      midentity,
      lv1_invite_code,
      real_name: leader_name,
      apply_reason: join_reason
    };
    API_Distribution.applyDistribution(_params).then(res => {
      wx.showToast({
        title: '您已成功提交分销团长申请，请等待审核结果',
        icon: 'none'
      });
    }).catch(error => {
      wx.showToast({
        title: error,
        icon: 'none'
      });
      this.setData({
        subDisabled: false
      });
    });
  },
  // 提交自提站点申请
  serviceApplyDPoint (_form) {
    delete _form.region_text;
    const { region, lat, lng } = this.data;
    _form = {
      ..._form,
      region,
      lat,
      lng,
      member_id: wx.getStorageSync('user').member_id
    }
    API_Leader.enrollLeader(_form).then(res => {
      wx.showToast({
        title: '您已成功提交自提站点申请，请等待审核结果',
        icon: 'none'
      });
    }).catch(error => {
      wx.showToast({
        title: error,
        icon: 'none'
      });
      this.setData({
        subDisabled: false
      });
    });
  }
});